<template>
  <div class="shoucang-page">
    <h2 class="section-title">我的收藏</h2>
    <p class="section-description">您收藏的花束和花艺作品</p>
    
    <div class="filter-bar">
      <div class="filter-tabs">
        <button 
          v-for="tab in tabs" 
          :key="tab.id"
          class="tab-btn"
          :class="{ 'active': activeTab === tab.id }"
          @click="activeTab = tab.id"
        >
          {{ tab.name }}
        </button>
      </div>
      
      <div class="filter-actions">
        <div class="search-box">
          <input type="text" placeholder="搜索收藏" v-model="searchQuery">
          <button class="search-btn" @click="searchCollections">🔍</button>
        </div>
        <button class="sort-btn" @click="toggleSortOrder">
          排序 <span class="sort-icon">{{ sortAscending ? '▲' : '▼' }}</span>
        </button>
      </div>
    </div>
    
    <div class="collection-grid" v-if="filteredCollections.length > 0">
      <div class="collection-card" v-for="item in filteredCollections" :key="item.id">
        <div class="card-header">
          <div class="card-image">
            <img :src="item.image" alt="收藏图片">
          </div>
          <button class="remove-btn" @click="removeFromCollection(item.id, item.type)">×</button>
        </div>
        <div class="card-body">
          <h3 class="card-title">{{ item.name }}</h3>
          <p class="card-price">¥{{ item.price }}</p>
          <div class="card-meta">
            <span class="card-date">收藏于 {{ formatDate(item.date) }}</span>
            <span class="card-type">{{ getTypeLabel(item.type) }}</span>
          </div>
          <div class="card-actions">
            <button class="btn-primary" @click="addToCart(item)">加入购物车</button>
            <router-link :to="`/diy?template=${item.id}`" class="btn-outline">查看详情</router-link>
          </div>
        </div>
      </div>
    </div>
    
    <div class="empty-state" v-else>
      <div class="empty-icon">❤️</div>
      <h3 class="empty-title">暂无收藏</h3>
      <p class="empty-description">您还没有收藏任何花束或花艺作品</p>
      <router-link to="/diy" class="btn-primary">浏览花束</router-link>
    </div>
    
    <div class="pagination" v-if="totalPages > 1">
      <button class="page-btn prev" @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <div class="page-numbers">
        <button 
          v-for="page in displayedPages" 
          :key="page" 
          class="page-number" 
          :class="{ 'active': currentPage === page }"
          @click="goToPage(page)"
        >
          {{ page }}
        </button>
        <span class="page-ellipsis" v-if="showEndEllipsis">...</span>
        <button 
          v-if="showLastPage"
          class="page-number" 
          :class="{ 'active': currentPage === totalPages }"
          @click="goToPage(totalPages)"
        >
          {{ totalPages }}
        </button>
      </div>
      <button class="page-btn next" @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
    
    <!-- 操作提示 -->
    <div class="toast" v-if="showToast">
      <div class="toast-content">
        <span class="toast-icon">{{ toastIcon }}</span>
        <span class="toast-message">{{ toastMessage }}</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserShouCang',
  data() {
    return {
      activeTab: 'all',
      searchQuery: '',
      sortAscending: false,
      currentPage: 1,
      itemsPerPage: 6,
      showToast: false,
      toastMessage: '',
      toastIcon: '',
      tabs: [
        { id: 'all', name: '全部收藏' },
        { id: 'custom', name: '自定义花束' },
        { id: 'ai', name: 'AI设计花束' },
        { id: 'recommended', name: '推荐花束' }
      ],
      favorites: []
    };
  },
  computed: {
    filteredCollections() {
      let result = [...this.favorites];
      
      // 按标签筛选
      if (this.activeTab !== 'all') {
        result = result.filter(item => item.type === this.activeTab);
      }
      
      // 按搜索词筛选
      if (this.searchQuery.trim()) {
        const query = this.searchQuery.toLowerCase().trim();
        result = result.filter(item => 
          item.name.toLowerCase().includes(query) || 
          this.getTypeLabel(item.type).toLowerCase().includes(query)
        );
      }
      
      // 排序
      result.sort((a, b) => {
        const dateA = new Date(a.date);
        const dateB = new Date(b.date);
        return this.sortAscending ? dateA - dateB : dateB - dateA;
      });
      
      return result;
    },
    paginatedCollections() {
      const startIndex = (this.currentPage - 1) * this.itemsPerPage;
      const endIndex = startIndex + this.itemsPerPage;
      return this.filteredCollections.slice(startIndex, endIndex);
    },
    totalPages() {
      return Math.ceil(this.filteredCollections.length / this.itemsPerPage);
    },
    displayedPages() {
      if (this.totalPages <= 5) {
        return Array.from({ length: this.totalPages }, (_, i) => i + 1);
      }
      
      if (this.currentPage <= 3) {
        return [1, 2, 3, 4, 5];
      }
      
      if (this.currentPage >= this.totalPages - 2) {
        return Array.from({ length: 5 }, (_, i) => this.totalPages - 4 + i);
      }
      
      return [this.currentPage - 2, this.currentPage - 1, this.currentPage, this.currentPage + 1, this.currentPage + 2];
    },
    showEndEllipsis() {
      return this.totalPages > 5 && this.currentPage < this.totalPages - 2;
    },
    showLastPage() {
      return this.totalPages > 5 && this.currentPage < this.totalPages - 2;
    }
  },
  created() {
    this.loadFavorites();
  },
  methods: {
    loadFavorites() {
      const storedFavorites = localStorage.getItem('userFavorites');
      if (storedFavorites) {
        this.favorites = JSON.parse(storedFavorites);
        // 确保每个收藏项都有图片
        this.favorites.forEach(item => {
          if (!item.image) {
            item.image = '@/assets/images/bouquet-preview.jpg';
          }
        });
      }
    },
    saveFavorites() {
      localStorage.setItem('userFavorites', JSON.stringify(this.favorites));
    },
    removeFromCollection(id, type) {
      if (confirm('确定要移除这个收藏吗？')) {
        const index = this.favorites.findIndex(item => item.id === id && item.type === type);
        if (index !== -1) {
          this.favorites.splice(index, 1);
          this.saveFavorites();
          this.showToastMessage('已从收藏中移除', '🗑️');
        }
      }
    },
    addToCart(item) {
      // 构建花束数据
      const bouquetData = {
        name: item.name,
        price: item.price,
        image: item.image,
        flowers: item.flowers || [],
        packaging: item.packaging || null,
        card: item.card || null,
        type: item.type
      };
      
      // 使用自定义事件发送数据到购物车组件
      const event = new CustomEvent('add-to-cart', { 
        detail: bouquetData,
        bubbles: true 
      });
      window.dispatchEvent(event);
      
      this.showToastMessage('已添加到购物车', '🛒');
    },
    searchCollections() {
      this.currentPage = 1; // 搜索时重置到第一页
    },
    toggleSortOrder() {
      this.sortAscending = !this.sortAscending;
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    },
    goToPage(page) {
      this.currentPage = page;
    },
    showToastMessage(message, icon) {
      this.toastMessage = message;
      this.toastIcon = icon;
      this.showToast = true;
      
      setTimeout(() => {
        this.showToast = false;
      }, 2000);
    },
    formatDate(dateString) {
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    getTypeLabel(type) {
      const typeMap = {
        'custom': '自定义花束',
        'ai': 'AI设计花束',
        'recommended': '推荐花束'
      };
      return typeMap[type] || type;
    }
  }
};
</script>

<style scoped>
.shoucang-page {
  color: #333;
}

.section-title {
  color: #e75480;
  margin-bottom: 0.5rem;
}

.section-description {
  color: #666;
  margin-bottom: 2rem;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.filter-tabs {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.tab-btn {
  padding: 0.6rem 1.2rem;
  background: none;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  color: #666;
}

.tab-btn:hover {
  border-color: #e75480;
  color: #e75480;
}

.tab-btn.active {
  background-color: #e75480;
  color: white;
  border-color: #e75480;
}

.filter-actions {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.search-box {
  position: relative;
}

.search-box input {
  padding: 0.6rem 2.5rem 0.6rem 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 200px;
  transition: all 0.3s;
}

.search-box input:focus {
  border-color: #e75480;
  outline: none;
  box-shadow: 0 0 0 2px rgba(231, 84, 128, 0.1);
}

.search-btn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  color: #999;
}

.sort-btn {
  padding: 0.6rem 1.2rem;
  background: none;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #666;
}

.sort-icon {
  font-size: 0.8rem;
}

.collection-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 2rem;
  margin-bottom: 2rem;
}

.collection-card {
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.collection-card:hover {
  transform: translateY(-5px);
}

.card-header {
  position: relative;
}

.card-image {
  height: 180px;
  overflow: hidden;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.8);
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  color: #666;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s;
}

.card-header:hover .remove-btn {
  opacity: 1;
}

.card-body {
  padding: 1.5rem;
}

.card-title {
  font-size: 1.2rem;
  margin-bottom: 0.5rem;
  color: #333;
}

.card-price {
  font-size: 1.3rem;
  font-weight: bold;
  color: #e75480;
  margin-bottom: 1rem;
}

.card-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 1.5rem;
  font-size: 0.9rem;
  color: #888;
}

.card-actions {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.8rem;
}

.btn-primary {
  padding: 0.8rem 1rem;
  background-color: #e75480;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  text-align: center;
  text-decoration: none;
  font-size: 0.9rem;
}

.btn-primary:hover {
  background-color: #d64d7b;
}

.btn-outline {
  padding: 0.8rem 1rem;
  background: none;
  border: 1px solid #e75480;
  color: #e75480;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
  font-size: 0.9rem;
  text-decoration: none;
  display: block;
}

.btn-outline:hover {
  background-color: #f8e1e7;
}

.empty-state {
  text-align: center;
  padding: 4rem 0;
  background-color: rgba(255, 255, 255, 0.5);
  border-radius: 12px;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.empty-title {
  font-size: 1.5rem;
  margin-bottom: 1rem;
  color: #333;
}

.empty-description {
  color: #666;
  margin-bottom: 2rem;
  max-width: 400px;
  margin-left: auto;
  margin-right: auto;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 2rem;
}

.page-btn {
  padding: 0.6rem 1.2rem;
  background: none;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  color: #666;
}

.page-btn:hover:not(:disabled) {
  border-color: #e75480;
  color: #e75480;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-btn.prev {
  margin-right: 1rem;
}

.page-btn.next {
  margin-left: 1rem;
}

.page-numbers {
  display: flex;
  align-items: center;
}

.page-number {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: none;
  border: 1px solid #ddd;
  margin: 0 0.3rem;
  border-radius: 4px;
  cursor: pointer;
  color: #666;
}

.page-number:hover {
  border-color: #e75480;
  color: #e75480;
}

.page-number.active {
  background-color: #e75480;
  color: white;
  border-color: #e75480;
}

.page-ellipsis {
  margin: 0 0.3rem;
  color: #666;
}

/* 提示框 */
.toast {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 0.8rem 1.5rem;
  border-radius: 30px;
  z-index: 1000;
  animation: fadeInOut 2s ease-in-out;
}

.toast-content {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.toast-icon {
  font-size: 1.2rem;
}

.toast-message {
  font-size: 0.9rem;
}

@keyframes fadeInOut {
  0% { opacity: 0; transform: translate(-50%, 20px); }
  20% { opacity: 1; transform: translate(-50%, 0); }
  80% { opacity: 1; transform: translate(-50%, 0); }
  100% { opacity: 0; transform: translate(-50%, -20px); }
}

@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-tabs {
    width: 100%;
    overflow-x: auto;
    padding-bottom: 0.5rem;
  }
  
  .filter-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .search-box input {
    width: 150px;
  }
}
</style>